﻿//--------------------------------------------------------------------------
//
//  File:        BoardControl.cs
//
//  Coder:       bigeagle@gmail.com
//
//  Date:        2013/1/28
//
//  Description: 棋盘控件类
//  
//  History:     2013/1/27 created by bigeagle  
//
//--------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Bigeagle.Portable.BoardGames;

using Windows.UI.Xaml.Shapes;
using Windows.UI;
using System.Diagnostics;
using Bigeagle.Portable.BoardGames.Go;
using System.Threading.Tasks;
using Windows.UI.Core;


// “用户控件”项模板在 http://go.microsoft.com/fwlink/?LinkId=234236 上提供

namespace Bigeagle.Metro.Games.Controls
{
    public  partial class BoardControl : UserControl
    {
        #region 成员变量


        /// <summary>
        /// 当前棋子
        /// </summary>
        Stone _CurrentStone = null;

        public Stone CurrentStone
        {
            get
            {
                return _CurrentStone;
            }
            set
            {
                _CurrentStone = value;
            }
        }

        /// <summary>
        /// 棋盘边缘
        /// </summary>
        double _BoardPadding = 30d;

        /// <summary>
        /// 默认宽度
        /// </summary>
        double _DefaultWidth = 600d;

        #endregion//end 成员变量

        #region 属性
        /// <summary>
        /// 棋盘
        /// </summary>
        private Board _Board;

        /// <summary>
        /// 设置或获得棋盘
        /// </summary>
        public Board GameBoard
        {
            get
            {
                return _Board;
            }
            set
            {
                if (_Board != null)
                {
                    _Board = value;
                }
            }
        }

        List<Stone> _BindingStones = new List<Stone>();

        public List<Stone> BindingStones
        {
            get
            {
                return _BindingStones;
            }

        }

        List<KiFUGame.Label> _BindingLabels = new List<KiFUGame.Label>();

        public List<KiFUGame.Label> BindingLabels
        {
            get
            {
                return _BindingLabels;
            }
        }

        /// 棋子控件数组
        /// </summary>
        StoneControl[,] _Stones;


        #endregion//end 属性

        #region 依赖属性

        #region 棋子直径属性
        public static readonly DependencyProperty StoneRadiusProperty =
            DependencyProperty.Register("StoneRadius", typeof(double), typeof(BoardControl)
            , new PropertyMetadata(10d, new PropertyChangedCallback(OnStoneRadiusChanged)));

        public double StoneRadius
        {
            get
            {
                return (double)GetValue(StoneRadiusProperty);
            }
            set
            {
                SetValue(StoneRadiusProperty, value);
            }
        }
        private static void OnStoneRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BoardControl control = (BoardControl)d;
            control.CaculateBoard();

        }
        #endregion//end 棋盘直径属性

        #region 棋盘线粗属性
        public static readonly DependencyProperty LineThicknessProperty =
            DependencyProperty.Register("LineThickness", typeof(double), typeof(BoardControl)
            , new PropertyMetadata(1d, new PropertyChangedCallback(OnLineThicknessChanged)));

        public double LineThickness
        {
            get
            {
                return (double)GetValue(LineThicknessProperty);
            }
            set
            {
                SetValue(LineThicknessProperty, value);
            }
        }
        private static void OnLineThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BoardControl control = (BoardControl)d;
            control.ChangeLineLineThickness((double)e.NewValue);

        }

        /// <summary>
        /// 改变线粗细
        /// </summary>
        /// <param name="thickness"></param>
        private void ChangeLineLineThickness(double thickness)
        {
            List<Line> lines = canvasMain.Children.Where(c => c is Line && (c as Line).Tag is int)
                .Select(c => c as Line).ToList();
            foreach (Line line in lines)
            {
                int i = (int)line.Tag;
                line.StrokeThickness = (i == 0 || i == _Board.BoardSize - 1) ? thickness * 2 : thickness;
            }
        }

        #endregion//end 棋盘线粗属性

        #region 棋盘背景属性
        public static readonly DependencyProperty BoardBackgroundProperty =
            DependencyProperty.Register("BoardBackground", typeof(Brush), typeof(BoardControl)
            , new PropertyMetadata(new SolidColorBrush(Color.FromArgb(0,243,225,43))
                , new PropertyChangedCallback(OnBoardBackgroundChanged)));

        public Brush BoardBackground 
        {
            get
            {
                return (Brush)GetValue(BoardBackgroundProperty);
            }
            set
            {
                SetValue(BoardBackgroundProperty, value);
            }
        }
        private static void OnBoardBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BoardControl control = (BoardControl)d;
            control.canvasMain.Background = e.NewValue as Brush;
        }

        #endregion//end 棋盘背景属性


        #endregion//end 依赖属性

        #region 事件

        /// <summary>
        /// 棋盘位置点击事件
        /// </summary>
        private BoardPositionEventHandler _BoardPositonClicked;

        /// <summary>
        /// 引发棋盘位置点击事件
        /// </summary>
        /// <param name="e"></param>
        protected void OnBoardPositionClicked(BoardPositionEventArgs e)
        {
            if (_BoardPositonClicked != null)
            {
                _BoardPositonClicked(this, e);
            }
        }

        /// <summary>
        /// 棋盘位置点击事件
        /// </summary>
        public event BoardPositionEventHandler BoardPositionClicked
        {
            add
            {
                _BoardPositonClicked += value;
            }
            remove
            {
                _BoardPositonClicked -= value;
            }
        }

        #endregion//end 事件

        /// <summary>
        /// 构造函数
        /// </summary>
        public BoardControl()
        {
            InitializeComponent();
            _Board = new Board();
            InitializeControls();
        }

        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitializeControls()
        {
            double w = canvasMain.ActualWidth == 0 ? _DefaultWidth : canvasMain.ActualWidth;
            w = w - _BoardPadding * 2;
            double d = w / (_Board.BoardSize -1);

            //画底色
            //this.canvasMain.Background = BoardBackground;
            //context.DrawRectangle(BoardBackground, null, new Rect(new Point(0,0) , new Size(w, h)));

            //画线
            List<UIElement> lines = canvasMain.Children.Where(c => c is Line).ToList();
            char ch = 'A';

            for (int i = 0; i < _Board.BoardSize; i++)
            {
                //
                //TODO:横线及坐标
                //
                Line linex = new Windows.UI.Xaml.Shapes.Line();
                linex.X1 = _BoardPadding;
                linex.Y1 = i * d + _BoardPadding;
                linex.X2 = w + _BoardPadding ;
                linex.Y2 = i * d + _BoardPadding;
                linex.Stroke = new SolidColorBrush(Windows.UI.Colors.Black);
                linex.StrokeThickness = LineThickness; ;
                linex.Tag = i;
                canvasMain.Children.Add(linex);

                TextBlock textTop = new TextBlock();
                
                textTop.Text = ch.ToString() ;
                textTop.Tag = ch.ToString();
                textTop.Width = FontSize;
                textTop.TextAlignment = TextAlignment.Center;

                Canvas.SetLeft(textTop, i  * d  + _BoardPadding - FontSize/2);
                Canvas.SetTop(textTop , 2);
                canvasMain.Children.Add(textTop);

                TextBlock textBottom = new TextBlock();

                textBottom.Text = ch.ToString();
                textBottom.Tag = ch.ToString();
                textBottom.Width = FontSize;
                textBottom.TextAlignment = TextAlignment.Center;
                Canvas.SetLeft(textBottom, i * d + _BoardPadding - FontSize / 2);
                Canvas.SetTop(textBottom, w + _BoardPadding * 2 - FontSize -2);
                canvasMain.Children.Add(textBottom);
                ch++;
                //
                //TODO:竖线
                //
                Line liney = new Windows.UI.Xaml.Shapes.Line();
                liney.Stroke = new SolidColorBrush(Windows.UI.Colors.Black);
                liney.StrokeThickness = (i == 0 | i == _Board.BoardSize) ? LineThickness * 2 : LineThickness;

                liney.X1 = i * d + _BoardPadding;
                liney.Y1 = _BoardPadding;
                liney.X2 = i * d + _BoardPadding;
                liney.Y2 = w + _BoardPadding;
                Debug.WriteLine("x1:{0} y1:{1} x2:{2} y2:{3}", liney.X1, liney.Y1, liney.X2, liney.Y2);
                liney.Tag =i;
                canvasMain.Children.Add(liney);


                TextBlock textLeft = new TextBlock();

                textLeft.Text = (_Board.BoardSize - i) .ToString();
                textLeft.Tag = (_Board.BoardSize - i).ToString();
                textLeft.TextAlignment = TextAlignment.Center;
                textLeft.Width = FontSize;
                Canvas.SetLeft(textLeft,  2);
                Canvas.SetTop(textLeft, i * d + _BoardPadding - FontSize/2);
                canvasMain.Children.Add(textLeft);

                TextBlock textRight = new TextBlock();

                textRight.Text = (_Board.BoardSize - i).ToString();
                textRight.Tag = (_Board.BoardSize - i).ToString();
                textRight.TextAlignment = TextAlignment.Center;
                textRight.Width = FontSize;
                Canvas.SetLeft(textRight, w + _BoardPadding * 2 -FontSize - 2);
                Canvas.SetTop(textRight, i * d + _BoardPadding - FontSize / 2);
                canvasMain.Children.Add(textRight);

            }
            
            //画星位
            for (int i = 3; i < 16; i += 6)
            {
                for (int j = 3; j < 16; j += 6)
                {

                    Ellipse ellipse = new Ellipse();
                    ellipse.Stroke = new SolidColorBrush(Colors.Black);
                    ellipse.Width = 5;
                    ellipse.Height = 5;
                    ellipse.Tag = new Point(i, j);
                    Canvas.SetLeft(ellipse, i * d - 2.5 + _BoardPadding);
                    Canvas.SetTop(ellipse, j * d - 2.5 + _BoardPadding);
                    canvasMain.Children.Add(ellipse);
                    //context.DrawEllipse(linePen.Brush, linePen, new Point(i * d, j * d), 3, 3);
                }
            }
            //context.Close();
            //VisualBrush drawingBrush = new VisualBrush();
            //drawingBrush.Visual = drawingVisual;
            //this.canvasMain.Background = drawingBrush;


            //初始化当前棋子标签

        }//end method

        void InitializeStones()
        {
            //初始化棋子控件数组
            double w = canvasMain.ActualWidth - _BoardPadding * 2;
            double d = w / (_Board.BoardSize - 1);

            _Stones = new StoneControl[_Board.BoardSize, _Board.BoardSize];
            for (int i = 0; i < _Board.BoardSize; i++)
            {
                for (int j = 0; j < _Board.BoardSize; j++)
                {
                    StoneControl control = new StoneControl();
                    control.BindingStone.X = i;
                    control.BindingStone.Y = j;
                    control.Width = StoneRadius * 2;
                    control.Height = StoneRadius * 2;
                    //double w = canvasMain.ActualWidth - _BoardPadding * 2;
                    //double d = w / (_Board.BoardSize - 1);

                    Canvas.SetLeft(control, d * i - StoneRadius + _BoardPadding);
                    Canvas.SetTop(control, d * j - StoneRadius + _BoardPadding);
                    Canvas.SetZIndex(control, 100);
                    control.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                    //this.canvasMain.Children.Add(control);

                    _Stones[i, j] = control;
                    //this.canvasMain.Children.Add(_Stones[i, j]);
                }
            }

        }

        /// <summary>
        /// 调整棋盘位置
        /// </summary>
        private void CaculateBoard()
        {
            
            //Pen linePen = new Pen(Brushes.Black, LineThickness);
            //DrawingVisual drawingVisual = new DrawingVisual();
            //DrawingContext context = drawingVisual.RenderOpen();
            //Windows.UI.Xaml.Media.Brush brush = null;
            ///重新计算位置
            double w = canvasMain.ActualWidth == 0 ? _DefaultWidth : canvasMain.ActualWidth;
            w = w - _BoardPadding * 2;
            double d = w  / (_Board.BoardSize - 1);

            //设置背景
            this.canvasMain.Background = BoardBackground;
            //context.DrawRectangle(BoardBackground, null, new Rect(new Point(0,0) , new Size(w, h)));

            //调整线和位置

            //调整横线竖线位置
            List<Line> lines = canvasMain.Children.Where(ue => ue is Line
                && (ue as Shape).Tag is int).Select(ue => ue as Line).ToList();
            foreach (Line line in lines)
            {
                int i = (int)line.Tag;
                if (line.Y1 == line.Y2) //横线
                {
                    line.X1 = _BoardPadding;
                    line.Y1 = i * d + _BoardPadding;
                    line.X2 = w + _BoardPadding;
                    line.Y2 = i * d + _BoardPadding;
                }
                else if (line.X2 == line.X1) //竖线
                {
                    line.X1 = i * d + _BoardPadding;
                    line.Y1 = _BoardPadding;
                    line.X2 = i * d + _BoardPadding ;
                    line.Y2 = w + _BoardPadding;

                }
            }

            //调整星位位置
            List<Ellipse> ellipses = canvasMain.Children.Where(ue => ue is Ellipse
                && (ue as Shape).Tag is Point).Select(ue => ue as Ellipse).ToList();
            foreach (Ellipse ellipse in ellipses)
            {
                Point point = (Point)ellipse.Tag;
                Canvas.SetLeft(ellipse, point.X * d - 2.5 + _BoardPadding);
                Canvas.SetTop(ellipse, point.Y * d - 2.5 + _BoardPadding);
            }
            
            //调整坐标标记位置
            List<string> xTags = new List<string>();
            List<string> yTags = new List<string>();
            char ch = 'A' ;
            for (int i = 0; i < _Board.BoardSize; i++)
            {
                xTags.Add(ch.ToString());
                yTags.Add((_Board.BoardSize - i).ToString());
                ch++;
            }
            List<TextBlock> blocks = canvasMain.Children
                .Where(ue => ue is TextBlock && (ue as TextBlock).Tag is string)
                .Select(ue => ue as TextBlock).ToList();

            foreach (TextBlock block in blocks)
            {
                Debug.WriteLine(block.Tag);
                int i = xTags.IndexOf(block.Tag as string);
                int j = yTags.IndexOf(block.Tag as string);
                if (i >= 0)
                {
                    Canvas.SetLeft(block, i * d + _BoardPadding - FontSize / 2);
                    if (Canvas.GetTop(block) > 2)  //如果是下边的坐标
                    {
                        Canvas.SetTop(block, w + _BoardPadding * 2 - FontSize - 2);

                    }
                }
                if (j >= 0)
                {
                    if (Canvas.GetLeft(block) > 2)
                    {
                        Canvas.SetLeft(block, w + _BoardPadding * 2 - FontSize - 2);
                    }
                    Canvas.SetTop(block, j * d + _BoardPadding - FontSize / 2);

                }
            }

            //调整已有的棋子
            List<StoneControl> stoneControls = canvasMain.Children
                .Where(ue => ue is StoneControl)
                .Select(ue => ue as StoneControl).ToList();

            foreach (StoneControl stone in stoneControls)
            {

                Canvas.SetLeft(stone, d * (stone.BindingStone.X) - StoneRadius + _BoardPadding);
                Canvas.SetTop(stone, d * (stone.BindingStone.Y) - StoneRadius + _BoardPadding);

            }
        }//end method


        /// <summary>
        /// 刷新
        /// </summary>
        /// <returns></returns>
        public async Task RefreshAsync()
        {
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, async delegate
            {

                for (int i = 0; i < _Board.BoardSize; i++)
                {
                    for (int j = 0; j < _Board.BoardSize; j++)
                    {
                        //_Stones[i,j].Visibility = Visibility.Collapsed;
                        Stone stone = _Board.GetPosition(i, j).TheStone;
                        if (stone == null)
                        {
                            _Stones[i, j].Visibility = Visibility.Collapsed;
                            canvasMain.Children.Remove(_Stones[i, j]);
                        }
                        else
                        {
                            _Stones[i, j].BindingStone = stone;
                            _Stones[i, j].Visibility = Windows.UI.Xaml.Visibility.Visible;

                            if (!canvasMain.Children.Contains(_Stones[i, j]))
                            {
                                canvasMain.Children.Add(_Stones[i, j]);
                            }

                            // await DrawStoneAsync(stone);
                        }
                    }
                }//end for

                //移除现有的标签及标记
                List<UIElement> marks = canvasMain.Children.Where(ue =>
                    (ue is Polygon && (ue as Polygon).Tag is Stone)
                    || ue is LabelControl).ToList();
                foreach (UIElement p in marks)
                {
                    canvasMain.Children.Remove(p);
                }
                
                //画新的标记及标签
                await DrawMark(_CurrentStone);
                if (_CurrentStone is CommentsMove)
                {
                    CommentsMove move = _CurrentStone as CommentsMove;
                    if (move.Labels.Count > 0)
                    {
                        IEnumerable<Task> tasks = from label in move.Labels
                                                  select DrawLabel(label);
                        await Task.WhenAll(tasks);
                    }
                }

            });
        }//end method

        

        /// <summary>
        /// 画当前手标签
        /// </summary>
        /// <param name="stone"></param>
        /// <returns></returns>
        async Task DrawMark(Stone stone)
        {
            await this.canvasMain.Dispatcher.RunAsync(CoreDispatcherPriority.High, delegate
            {
                Polygon mark = new Polygon();
                mark.Tag = stone;
                mark.Fill = new SolidColorBrush(Colors.Red);
                double w = StoneRadius * 2;
                double h = StoneRadius * 2;
                mark.Points.Add(new Point(w / 5 * 2, h / 5 * 1));
                mark.Points.Add(new Point(w / 5 * 4, h / 2));
                mark.Points.Add(new Point(w / 5 * 2, h / 5 * 4));

                Canvas.SetLeft(mark, Canvas.GetLeft(_Stones[stone.X, stone.Y]));
                Canvas.SetTop(mark, Canvas.GetTop(_Stones[stone.X, stone.Y]));
                Canvas.SetZIndex(mark, 200);
                canvasMain.Children.Add(mark);
            });
        }

        /// <summary>
        /// 根据点找到棋盘位置
        /// </summary>
        /// <param name="point"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private void GetPosition(Point point, out int x, out int y)
        {
            x = -1;
            y = -1;
            double w = canvasMain.ActualWidth == 0 ? _DefaultWidth : canvasMain.ActualWidth;
            w = w - _BoardPadding * 2;
            double d = w  / (_Board.BoardSize - 1);

            for (int i = 0; i < _Board.BoardSize; i++)
            {
                for (int j = 0; j < _Board.BoardSize; j++)
                {
                    Point p = new Point(i * d + _BoardPadding, j * d + _BoardPadding);
                    if (CaculateDistance(p, point) <= 5)
                    {
                        x = i;
                        y = j;
                        return;
                    }
                }
            }
        }//end method

        /// <summary>
        /// 计算屏幕两点之间的距离
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns>距离</returns>
        double CaculateDistance(Point p1, Point p2)
        {
            double x = Math.Abs(p1.X - p2.X);
            double y = Math.Abs(p1.Y - p2.Y);
            return Math.Sqrt(x * x + y * y);
        }

        /// <summary>
        /// 测试点是否在热点上
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        private bool IsInPoint(Point point)
        {
            int x = -1 , y = -1;
            GetPosition(point , out x , out y) ;
            return x > -1 && y > -1;
        }

        /// <summary>
        /// canvas载入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvasMain_Loaded(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// 控件大小改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _DefaultWidth = e.NewSize.Width;
            this.CaculateBoard();
        }

        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvasMain_Tapped(object sender, TappedRoutedEventArgs e)
        {
            int x, y;
            
                Point point = e.GetPosition(this.canvasMain);
                GetPosition(point, out x, out y);
                if (x > -1 && y > -1)
                {
                    OnBoardPositionClicked(new BoardPositionEventArgs(x, y));
                }

        }

    //    /// <summary>
    //    /// 鼠标左键弹起事件
    //    /// </summary>
    //    /// <param name="sender"></param>
    //    /// <param name="e"></param>
    //    private void canvasMain_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    //    {
    //        int x, y;
    //        if (e.ClickCount == 1)
    //        {
    //            Point point = e.GetPosition(this.canvasMain);
    //            GetPosition(point, out x, out y);
    //            if (x > -1 && y > -1)
    //            {
    //                OnBoardPositionClicked(new BoardPositionEventArgs(x, y));
    //            }
    //            //if (x != -1 && y != -1)
    //            //{
    //            //    MessageBox.Show(string.Format("{0} , {1}" , x , y)) ;
    //            //}
    //        }
    //    }//end method

        ///// <summary>
        ///// 画棋子
        ///// </summary>
        ///// <param name="stone"></param>
        //private void DrawStone(Stone stone)
        //{
        //    StoneControl control = new StoneControl();
        //    control.BindingStone = stone;
        //    control.Width = StoneRadius * 2;
        //    control.Height = StoneRadius * 2;
        //    double w = canvasMain.ActualWidth - _BoardPadding * 2;
        //    double d = w / (_Board.BoardSize - 1);

        //    Canvas.SetLeft(control, d * (stone.X) - StoneRadius + _BoardPadding);
        //    Canvas.SetTop(control, d * (stone.Y) - StoneRadius + _BoardPadding);
        //    //control.IsShowMark = false;
        //    this.canvasMain.Children.Add(control);
        //    ////清除上一个子的标记
        //    //if (_LastStone != null)
        //    //{
        //    //    _LastStone.IsShowMark = false;
        //    //}

        //    //_LastStone = control;

        //}//end method


        ///// <summary>
        ///// 画棋子
        ///// </summary>
        ///// <param name="stone"></param>
        //private async Task DrawStoneAsync(Stone stone)
        //{
        //    await canvasMain.Dispatcher.RunAsync(CoreDispatcherPriority.High, delegate
        //    {
        //        StoneControl control = new StoneControl();
        //        control.BindingStone = stone;
        //        control.Width = StoneRadius * 2;
        //        control.Height = StoneRadius * 2;
        //        double w = canvasMain.ActualWidth - _BoardPadding * 2;
        //        double d = w / (_Board.BoardSize - 1);

        //        Canvas.SetLeft(control, d * (stone.X) - StoneRadius + _BoardPadding);
        //        Canvas.SetTop(control, d * (stone.Y) - StoneRadius + _BoardPadding);
        //        //control.IsShowMark = true;
        //        this.canvasMain.Children.Add(control);

        //        //Stone lastStone = _BindingStones.OrderBy(c => c.Step).LastOrDefault();
        //        //IEnumerable<StoneControl> controls = canvasMain.Children
        //        //    .Where(c => c is StoneControl 
        //        //        && (c as StoneControl).BindingStone != lastStone 
        //        //        && (c as StoneControl).IsShowMark)
        //        //        .Select(c => c as StoneControl);
        //        //foreach (StoneControl c in controls)
        //        //{
        //        //    c.IsShowMark = false;
        //        //}
                
        //    });
        //}//end method


        ///// <summary>
        ///// 强制放置棋子，不引发任何事件
        ///// </summary>
        //private void ForceDrawStone(Stone stone)
        //{
        //    StoneControl control = new StoneControl();
        //    control.BindingStone = stone;
        //    control.Width = StoneRadius * 2;
        //    control.Height = StoneRadius * 2;
        //    double w = canvasMain.ActualWidth - _BoardPadding * 2;
        //    double d = w / (_Board.BoardSize - 1);

        //    Canvas.SetLeft(control, d * (stone.X) - StoneRadius + _BoardPadding);
        //    Canvas.SetTop(control, d * (stone.Y) - StoneRadius + _BoardPadding);
        //    this.canvasMain.Children.Add(control);
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="label"></param>
        private async Task DrawLabel(KiFUGame.Label label)
        {
            await this.canvasMain.Dispatcher.RunAsync(CoreDispatcherPriority.High, delegate
            {
                LabelControl control = new LabelControl();
                control.Width = StoneRadius * 2;
                control.Height = StoneRadius * 2;
                control.Tag = label;
                control.Text = label.Name.ToLower();
                control.LabelBackground = this.BoardBackground;
                //textBlock.Style = 
                double w = canvasMain.ActualWidth - _BoardPadding * 2;
                double d = w / (_Board.BoardSize - 1);

                Canvas.SetLeft(control, d * label.X - StoneRadius + _BoardPadding);
                Canvas.SetTop(control, d * label.Y - StoneRadius + _BoardPadding);

                canvasMain.Children.Add(control);
            });
        }

        ///// <summary>
        ///// 移除棋子
        ///// </summary>
        ///// <param name="stone"></param>
        //private void RemoveStone(Stone stone)
        //{
        //    UIElement c = canvasMain.Children.Where(ue => ue is StoneControl 
        //        && (ue as StoneControl).BindingStone == stone).FirstOrDefault();
        //    if (c != null)
        //    {
        //        this.canvasMain.Children.Remove(c);
        //    }
        //}

        ///// <summary>
        ///// 移除棋子
        ///// </summary>
        ///// <param name="stone"></param>
        //private async Task RemoveStoneAsync(Stone stone)
        //{
        //    await canvasMain.Dispatcher.RunAsync(CoreDispatcherPriority.High, delegate
        //    {
        //        UIElement c = canvasMain.Children.Where(ue => ue is StoneControl
        //            && (ue as StoneControl).BindingStone == stone).FirstOrDefault();
        //        if (c != null)
        //        {
        //            this.canvasMain.Children.Remove(c);
        //        }
        //    });
        //}

        ///// <summary>
        ///// 移除棋子
        ///// </summary>
        ///// <param name="x">横坐标</param>
        ///// <param name="y">纵坐标</param>
        //public void RemoveStone(int x, int y)
        //{
        //    StoneControl sc = GetStoneControl(x, y);
        //    if (sc != null)
        //    {
        //        canvasMain.Children.Remove(sc);
        //    }
        //}

        /// <summary>
        /// 根据坐标取得棋子控件
        /// </summary>
        /// <param name="x">横坐标</param>
        /// <param name="y">纵坐标</param>
        /// <returns></returns>
        private StoneControl GetStoneControl(int x, int y)
        {
            return canvasMain.Children.Where(ue => ue is StoneControl 
                && (ue as StoneControl).BindingStone.X == x 
                && (ue as StoneControl).BindingStone.Y == y).FirstOrDefault() as StoneControl;
        }//end method

        //public void Reset()
        //{
        //    _BindingStones.Clear();
        //    ClearLabels();
        //    List<UIElement> stones = canvasMain.Children.Where(ue => ue is StoneControl || ue is LabelControl).ToList();
        //    for (int i = 0; i < stones.Count; i++)
        //    {
        //        canvasMain.Children.Remove(stones[i]);
        //    }
        //    _Board.InitPositions();
        //}//end method

        public void ClearLabels()
        {
            List<UIElement> labels = canvasMain.Children.Where(ue =>ue is LabelControl).ToList();
            for (int i = 0; i < labels.Count; i++)
            {
                canvasMain.Children.Remove(labels[i]);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //CaculateBoard();
            if (ActualWidth > 0)
            {
                _DefaultWidth = ActualWidth;
            }

            InitializeStones();
            CaculateBoard();
        }//end method

    }//end class

    #region 棋盘位置委托及事件参数

    /// <summary>
    /// 棋盘位置委托
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    public delegate void BoardPositionEventHandler(object sender, BoardPositionEventArgs e);

    /// <summary>
    /// 棋盘位置事件参数
    /// </summary>
    public class BoardPositionEventArgs : System.EventArgs
    {
        /// <summary>
        /// 横坐标
        /// </summary>
        int _X = 0;

        /// <summary>
        /// 纵坐标
        /// </summary>
        int _Y = 0;

        /// <summary>
        /// 设置或获得横坐标
        /// </summary>
        public int X
        {
            get
            {
                return _X;
            }
            set
            {
                _X = value;
            }
        }

        /// <summary>
        /// 设置或获得纵坐标
        /// </summary>
        public int Y
        {
            get
            {
                return _Y;
            }
            set
            {
                _Y = value;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public BoardPositionEventArgs()
        {
        }

        /// <summary>
        /// 重载构造函数
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public BoardPositionEventArgs(int x, int y)
        {
            _X = x;
            _Y = y;
        }
    }//end class

    #endregion 棋盘位置委托及事件参数

}//end namespace    
